package come.example.pagetransformer.transform

import android.support.v4.view.ViewPager
import android.view.View
import kotlin.math.pow

class AlphaTransformer constructor(fromPosition: Float) : ViewPager.PageTransformer {
    private var mOffSetPosition = 0.9F
    private var mMax = 0.9F
    private var mMin = 0.1F

    init {
        mOffSetPosition = when {
            fromPosition < 0.1f -> mMin
            fromPosition < 0.9f -> fromPosition
            else -> mMax
        }
    }


    override fun transformPage(view: View, position: Float) {
        var pos = position
        if (position < -mOffSetPosition) {
            view.alpha = getAlpha(mOffSetPosition) * (1 + pos)
        } else if (pos >= -mOffSetPosition && pos < mOffSetPosition) {
            view.alpha = 1.0f
        } else if (pos >= mOffSetPosition) {
            view.alpha = getAlpha(mOffSetPosition) * (1 - pos)
        }
    }

    private fun getAlpha(alpha: Float): Float {
        val realAlpha = 636.38 * alpha.pow(6) -
                    1679.2 * alpha.pow(5) +
                    1784.1 * alpha.pow(4) -
                    950.95 * alpha.pow(3) +
                    263.56 * alpha.pow(2) -
                    33.363 * alpha + 2.605
        return realAlpha.toFloat()
    }

    companion object {
        private val TAG = AlphaTransformer::class.java.simpleName
    }
}
